package cn.jingyuan.swan.uaa.service.impl;

import cn.jingyuan.bee.utils.BooleanUtils;
import cn.jingyuan.swan.cloud.core.Result;
import cn.jingyuan.swan.cloud.oauth2.DefaultAuthority;
import cn.jingyuan.swan.system.model.ClientDetails;
import cn.jingyuan.swan.uaa.helper.SysAuthorityHelper;
import cn.jingyuan.swan.uaa.service.feign.AppService;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Map;

@Service("defaultClientDetailsService")
public class ClientDetailsServiceImpl implements ClientDetailsService {

    @Resource
    AppService sysAppService;

    @Override
    public org.springframework.security.oauth2.provider.ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        Result<ClientDetails> clientDetailsResult = sysAppService.getAppClientInfo(clientId);
        ClientDetails sysClientDetails = clientDetailsResult.getData();
        if (sysClientDetails == null) {
            throw new NoSuchClientException("No client with requested id: " + clientId);
        }

        Map<String, Object> information = sysClientDetails.getAdditionalInformation();
        String status = information.get("status").toString();
        if (null != status && BooleanUtils.isFalse(status)) {
            throw new ClientRegistrationException("The client is disabled");
        }

        Collection<DefaultAuthority> defaultAuthorities = SysAuthorityHelper.to(sysClientDetails.getAuthorities());

        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(sysClientDetails.getClientId());
        clientDetails.setAutoApproveScopes(sysClientDetails.getAutoApproveScopes());
        clientDetails.setClientSecret(sysClientDetails.getClientSecret());
        clientDetails.setScope(sysClientDetails.getScope());
        clientDetails.setResourceIds(sysClientDetails.getResourceIds());
        clientDetails.setAuthorizedGrantTypes(sysClientDetails.getAuthorizedGrantTypes());
        clientDetails.setRegisteredRedirectUri(sysClientDetails.getRegisteredRedirectUris());
        clientDetails.setAuthorities(defaultAuthorities);
        clientDetails.setAccessTokenValiditySeconds(sysClientDetails.getAccessTokenValiditySeconds());
        clientDetails.setRefreshTokenValiditySeconds(sysClientDetails.getRefreshTokenValiditySeconds());
        clientDetails.setAdditionalInformation(information);

        return clientDetails;
    }

}
